from __future__ import absolute_import

import errno
import json
import os
import os.path as osp
import warnings


def mkdir_if_missing(directory):
    if not osp.exists(directory):
        try:
            os.makedirs(directory)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise


def check_isfile(path):
    isfile = osp.isfile(path)
    if not isfile:
        warnings.warn('No file found at "{}"'.format(path))
    return isfile


def read_json(fpath):
    with open(fpath, 'r') as f:
        obj = json.load(f)
    f.close()
    return obj


def write_json(obj, fpath):
    mkdir_if_missing(osp.dirname(fpath))
    with open(fpath, 'w') as f:
        json.dump(obj, f, indent=4, separators=(',', ': '))
    f.close()


def init_state(fpath):
    """
    初始化状态码文件，将状态码置为-1
    @param fpath:
    @return:
    """
    state_dict = {
        "batch": "0xcs",
        "uavType": "213",
        "uav": "UAV123",
        "state": -1,
        "id": "00001117",
        "classify": "052D"
    }
    write_json(obj=state_dict, fpath=fpath)


def reset_state_file(fpath):
    """
    重置状态文件，重置状态码为-1，其余不变
    """
    with open(fpath, 'r') as f:
        data = json.load(f)

    data["state"] = -1
    with open(fpath, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)
